<?php

/**
 * tuan.php
 *
 * Author: netman
 * DateTime:  2023/10/12 10:37
 */
class Service_Api_Tuan extends Contract_Api_Product
{
    use Trait_Api_Tuan;
    use Trait_Api_Common;

    /**
     * 类型ID
     */
    const TYPE_ID = 13;
    /**
     * @var Service_Api_Fenxiao
     */
    private $fenxiao_service = null;

    public function __construct()
    {
        $this->fenxiao_service = new Service_Api_Fenxiao();
    }

    /**
     * 产品搜索
     * @param  array  $params
     * @return array
     * User: netman
     * Date: 2023/9/11 17:47
     */
    function search(array $params = array()): array
    {
        $status = true;
        if ($params['destpy'] == 'quanbu' || empty($params['destpy'])) {
            $builder = $this->tuan_query($params,'`sline_tuan`.*,(IFNULL(`sline_tuan`.bookcount,0)+IFNULL(d.sell,0)) AS sellnum');
            $builder_count = $this->tuan_query($params,'`sline_tuan`.id');
        } else {
            $builder = $this->tuan_query_dest($params,'`sline_tuan`.*,(IFNULL(`sline_tuan`.bookcount,0)+IFNULL(d.sell,0)) AS sellnum');
            $builder_count = $this->tuan_query_dest($params,'`sline_tuan`.id');
        }
        //查询目的地ID
        if ($params['destpy'] != 'quanbu' && $params['destpy']) {
            $dest_id = DB::select('id')->from('destinations')->where('pinyin', '=',
                $params['destpy'])->execute()->get('id');
            $builder->and_where(DB::expr(" and FIND_IN_SET(".$dest_id.",sline_tuan.kindlist)"));
            $builder_count->and_where(DB::expr(" and FIND_IN_SET(".$dest_id.",sline_tuan.kindlist)"));
        }
        //按状态 1：进行中 2：未开始 0 已过期 3,已售完
        if ($params['status'] == 2) {
            $builder->and_where("tuan.starttime", '>', time());
            $builder_count->and_where("tuan.starttime", '>', time());
        }
        if ($params['status'] == 1) {
            $builder->and_where("tuan.starttime", '<=', time());
            $builder->and_where("tuan.endtime", '>', time());

            $builder_count->and_where("tuan.starttime", '<=', time());
            $builder_count->and_where("tuan.endtime", '>', time());
        }

        //按属性
        if ( ! empty($params['attrid'])) {
            $builder->and_where(DB::expr($this->get_attr_where($params['attrid'])));
            $builder_count->and_where(DB::expr($this->get_attr_where($params['attrid'])));
        }
        //分页
        if ( ! isset($params['page'])) {
            $params['page'] = 1;
        }
        //排序
        switch ($params['sorttype']) {
            case 1:
                $builder->order_by(DB::expr("sline_tuan.price asc"));
                break;
            case 2:
                $builder->order_by(DB::expr("sline_tuan.price desc"));
                break;
            case 3:
                $builder->order_by(DB::expr("sline_tuan.virtualnum desc"));
                break;
            case 4:
                $builder->order_by(DB::expr("sline_tuan.shownum desc"));
                break;
            default:
                $builder->order_by(DB::expr("IFNULL(sline_b.displayorder,9999) ASC"));
                $builder->order_by(DB::expr("sline_tuan.modtime desc"));
                $builder->order_by(DB::expr("sline_tuan.addtime desc"));
                break;
        }
        //关键词
        if ( ! empty($params['keyword'])) {
            $builder->and_where(DB::expr(' and sline_tuan.title like '.'"%'.$params['keyword'].'%"'));
            $builder_count->and_where(DB::expr(' and sline_tuan.title like '.'"%'.$params['keyword'].'%"'));
        }
        //总数量
        $total = $builder_count->execute()->count();

        $page = $params['page'];
        $pagesize = $params['pagesize'];
        //是否超限判断
        $total_page = (int)ceil($total / $params['pagesize']);
        if (($total_page > 0 and $page > $total_page) or ($total_page == 0 and $page > 1)) {
            $status = false;
        }
        if ($page && $pagesize) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }
        $arr = $builder->execute()->as_array();
        $arr = $this->format_tuan($arr, $params['mid']);
        $out = array(
            'total'  => $total,
            'list'   => $arr,
            'status' => $status
        );
        return $out;
    }

    /**
     * 全局排序
     * @param $params
     * @param $field
     * @return Database_Query_Builder_Select
     */
    public function tuan_query($params,$field){
        return DB::select(DB::expr($field))
            ->from('tuan')
            ->distinct(true)
            ->join(DB::expr("(SELECT sum(dingnum) as sell,`sline_member_order`.productautoid FROM `sline_member_order` WHERE `sline_member_order`.typeid=13 GROUP BY `sline_member_order`.productautoid) AS d"),
                'left')
            ->on(DB::expr('d.productautoid'), '=', 'tuan.id')
            ->join(array('allorderlist', 'b'), 'left')
            ->on("tuan.id", '=', 'b.aid')
            ->on('b.typeid', '=', self::TYPE_ID)
            ->on('tuan.webid', '=', 'b.webid')
            ->where('tuan.endtime', '>', time())
            ->and_where(DB::expr(" and FIND_IN_SET({$params['platform_no']},sline_tuan.platform)"))
            ->and_where('tuan.status', '=', 3);
    }

    /**
     * 目的地排序
     * @param $params
     * @param $field
     * @return Database_Query_Builder_Select
     *
     */
    public function tuan_query_dest($params,$field){
        return DB::select(DB::expr($field))
            ->from('tuan')
            ->distinct(true)
            ->join(DB::expr("(SELECT sum(dingnum) as sell,`sline_member_order`.productautoid FROM `sline_member_order` WHERE `sline_member_order`.typeid=13 GROUP BY `sline_member_order`.productautoid) AS d"),
                'left')
            ->on(DB::expr('d.productautoid'), '=', 'tuan.id')
            ->join(array('kindorderlist', 'b'), 'left')
            ->on("tuan.id", '=', 'b.aid')
            ->on('b.typeid', '=', self::TYPE_ID)
            ->on('tuan.webid', '=', 'b.webid')
            ->where('tuan.endtime', '>', time())
            ->and_where(DB::expr(" and FIND_IN_SET({$params['platform_no']},sline_tuan.platform)"))
            ->and_where('tuan.status', '=', 3);
    }

    /**
     * 产品详情
     * @param  array  $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/11 16:39
     */
    function info(array $params = array()): array
    {
        $product_id = $params['product_id'];
        $mid = $params['mid'];

        $info = DB::select()->from('tuan')
            ->where('id', '=', $product_id)
            ->where(DB::expr(" and FIND_IN_SET({$params['platform_no']},platform)"))
            ->where('id', '=', $product_id)
            ->where('status', '=', 3)
            ->execute()
            ->current();
        if ( ! $info) {
            throw new Exception("未找到团购产品");
        }
        //seo
        $seo_info = Product::seo($info);
        $info['seo_info'] = $seo_info;
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID,2);
        if(isset($uni_img['litpic'][$info['id']])){
            $info['litpic'] = $uni_img['litpic'][$info['id']];
            $info['piclist'] = $uni_img['piclist'][$info['id']];
        }
        //产品图片
        $piclist = Product::pic_list($info['piclist']);
        $p = array();
        foreach ($piclist as &$pic) {
            $pi = $this->img_url($pic[0], 750, 750);
            array_push($p, $pi);
        }
        if (empty($p)) {
            $p[0] = $this->img_url('');
        }
        $info['piclist'] = $p;
        //属性列表
        $info['attrlist'] = Model_Tuan::attr($info['attrid']);
        $info['price'] = Model_Tuan::get_minprice($info['id'], array('info' => $info));
        //会员折扣
        if ($mid) {
            $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $product_id,
                $info['price']);
        }
        //点评数
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::TYPE_ID);
        $info['sellpoint']=$info['sellpoint']?:'';
        //销售数量
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::TYPE_ID) + (int)$info['virtualnum'];
        //产品编号
        $info['series'] = St_Product::product_series($info['id'], self::TYPE_ID);
        //产品图标
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);
        //满意度
        $info['satisfyscore'] = St_Functions::get_satisfy(self::TYPE_ID, $info['id'], $info['satisfyscore']);
        $info['litpic'] = $this->img_url($info['litpic']);
        $info['basehost'] = $GLOBALS['cfg_basehost'];
        $info['content'] = $this->content_add_domain($info['content']);
        $info['status'] = $this->get_tuan_status($info);
        $info['starttime'] = (int)($info['starttime']);
        $info['endtime'] = (int)($info['endtime']);

        //扩展字段信息
        $extend_info = ORM::factory('tuan_extend_field')
            ->where("productid=".$info['id'])
            ->find()
            ->as_array();
        $info['extend_info'] = $extend_info;
        //详情内容
        $params = array(
            'typeid' => self::TYPE_ID,
            'productinfo' => $info,
            'pc' => 0
        );
        $info['detail_list'] = $this->get_detail_content($params);
        //分销赚取的金额
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            $info['profit'] = $this->fenxiao_service->get_estimate_profit(self::TYPE_ID, $mid, $info['id'],
                $info['price']);
        }
        // 积分抵现配置
        $jifenprice_info = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
        $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'),
            $jifenprice_info);
        // 预定送积分
        $jifenbook_info = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
        $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);
        // 更加ID查询可用的优惠券
        if (St_Functions::is_normal_app_install('coupon')) {
            $coupon_list = Model_Coupon::xcx_get_product_coupon_list($info['id'], self::TYPE_ID, $mid);
            $coupons = [];
            foreach ($coupon_list as $coupon) {
                $coupons[] = $this->filter_data(array('id', 'name'), $coupon);
            }
            $info['coupon_list'] = $coupons;
        }
        //供应商
        if ($info['supplierlist']) {
            $info['suppliers'] = DB::select('suppliername', 'id')->from('supplier')->where('id', '=',
                $info['supplierlist'])->execute()->current();
        }

        // 退款规则
        $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
        $info['refund_rule']  = $refund_class->get_format_refund_rule(0, $product_id);

        //折扣
        if($info['sellprice']){
            $discount = bcdiv($info['price'],$info['sellprice'],2);
            $discount = bcmul($discount,10,1);
            if ($discount == round($discount)) {
                $info['discount'] = intval($discount); // 如果小数位是0，则转换为整数
            } else {
                $info['discount'] = number_format($discount, 2); // 如果小数位不是0，则保留2位小数
            }
        }

        $fields = 'id,title,sellpoint,seo_info,sellprice,price,discount_min_price,litpic,starttime,endtime,attrlist,discount,';
        $fields .= 'series,iconlist,score,litpic,piclist,basehost,status,content,extend_info,detail_list,profit,jifentprice_info,';
        $fields .= 'jifenbook_info,jifencomment_info,refund_restriction,paytype,sellnum,commentnum,suppliers,coupon_list,ishidden,';
        $fields .= 'dingjin,fill_tourer_type,paytype,limit_number,receive_address,limit_order,price_type,refund_rule,satisfyscore';

        return $this->filter_data($fields, $info);
    }

    /**
     * 产品查询条件
     * @return array
     * User: netman
     * Date: 2023/9/11 17:48
     */
    function query_condition(): array
    {
        $sort = Kohana::$config->load('condition.tuan.sort');
        $result = array(
            'sort' => $sort
        );
        //属性
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('tuan_attr')->where('pid', '=',
            0)->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'),
            'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item) {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('tuan_attr')->where('pid', '=',
                $item['id'])->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'),
                'asc')->execute()->as_array();
        }
        return $result;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/13 16:24
     * @throws Kohana_Exception
     * @throws Exception
     */
    function create_order(array $params = array()): array
    {
        $mid         = $params['mid'];

        // 创建订单信息
        $result = $this->make_order($params);
        $order = $result['data'];

        // 订单编号
        $order['ordersn'] = Product::get_ordersn('13');

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        // 保存订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Tuan');
        if ($out['status']) {
            $order_info = Model_Member_Order::order_info($order['ordersn']);
            $order_id = $order_info['id'];
            $order_info['orderid'] = $order_id;

            // 游客信息
            $tourist = $params['tourist'];
            if ($tourist) {
                $tourist = json_decode($tourist);
            }
            //游客信息保存
            $arr = array();
            foreach ($tourist as $k => $v) {
                $arr['orderid'] = $order_id;
                $arr['tourername'] = $v->tourername;
                $arr['sex'] = $v->sex ? $v->sex : '';
                $arr['mobile'] = $v->mobile ? $v->mobile : '';
                $arr['cardtype'] = $v->cardtype ? $v->cardtype : '';
                $arr['cardnumber'] = $v->cardnumber ? $v->cardnumber : '';
                $arr['birth'] = $v->birth ? $v->birth : '';
                DB::insert('member_order_tourer', array_keys($arr))->values(array_values($arr))->execute();
            }

            // 优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }

            //添加红包抵扣
            $envelope_member_id = Arr::get($params, 'envelope_member_id', '');
            if($envelope_member_id) {
                if (St_Functions::is_normal_app_install('red_envelope')) {
                    Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
                }
            }

            //订单结算信息表数据更新
            Model_Member_Order_Compute::update($order['ordersn']);

            // 订单创建完成事件
            Hook::trigger('order_created', $order_info);

            // 返回订单信息
            $filter_keys = array('id', 'orderid', 'ordersn', 'paytype', 'typeid', 'status');
            return $this->filter_data($filter_keys, $order_info);
        } else {
            throw new Exception($out['msg']);
        }
    }


}